package zcatt.ex002.ui.contribution;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.eclipse.jface.action.IContributionItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.CompoundContributionItem;
import org.eclipse.ui.menus.CommandContributionItem;
import org.eclipse.ui.menus.CommandContributionItemParameter;

public class DynamicMenuListContributionItem extends CompoundContributionItem {

	private static final IContributionItem[] EMPTY = new IContributionItem[0];
	public static String KEY = "DynamicMenumList";
	

	@Override
	protected IContributionItem[] getContributionItems() {

		IWorkbenchWindow window = PlatformUI.getWorkbench()
				.getActiveWorkbenchWindow();
		if (window == null) {
			return EMPTY;
		}

		Shell shell = window.getShell();
		List<String> itemList = (List<String>) shell.getData(KEY);
		if(itemList == null)
		{
			itemList = new ArrayList<String>();
			shell.setData(KEY, itemList);			
		}
		
		ArrayList<IContributionItem> menuList = new ArrayList<>();

		for (int i = 0; i < itemList.size() && i < 10; i++) {
			menuList.add(createItem(i+1, itemList.get(i)));
		}
		if(menuList.isEmpty())
			menuList.add(createItem(0, "no item"));
		
		return menuList.toArray(new IContributionItem[menuList.size()]);
	}
	
	private IContributionItem createItem(int i, String name) {
		CommandContributionItemParameter p = new CommandContributionItemParameter(
				PlatformUI.getWorkbench(), null, HelloMessageHandler.ID,
				CommandContributionItem.STYLE_PUSH);
		p.parameters = new HashMap<>();
		if(i > 0)
		{
			p.label = name + " " + i;			
		}
		else
			p.label = name;
		
		return new CommandContributionItem(p);
	}
	

}
